package com.zhongkun.datahome.web.core.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zhongkun.datahome.common.constant.Constants;
import com.zhongkun.datahome.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.fillStrategy(metaObject, "createBy", SecurityUtils.getTenantUserId());
        this.fillStrategy(metaObject, "updateBy", SecurityUtils.getTenantUserId());
        this.fillStrategy(metaObject, "createTime", new Date());
        this.fillStrategy(metaObject, "tenantId", getTenantId());
        this.fillStrategy(metaObject, "delFlag", Constants.NOT_DELETE);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateBy", SecurityUtils.getTenantUserId(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }

    private Long getTenantId() {
        Long tenantId = SecurityUtils.getTenantId();
        return tenantId == null ? 0L : tenantId;
    }
}